const { exec } = require('child_process');
const { promisify } = require('util');
const path = require('path');
const fs = require('fs-extra');
const dependencyResolver = require('./dependencyResolver');
const logManager = require('./logManager');

const execAsync = promisify(exec);

/**
 * Docker化构建管理器 - 真正支持多Node版本
 */
class DockerBuildManager {
  constructor() {
    // Node版本到Docker镜像的映射 (使用Debian基础镜像以更好支持node-gyp)
    this.nodeImages = {
      'node14': 'node:14.21.3-bullseye', // 使用Debian以修复Python兼容性
      'node16': 'node:16.20.2-bullseye', 
      'node18': 'node:18.18.2-bullseye',
      'node22': 'node:22.18.0-bullseye'
    };
  }

  /**
   * 检查Docker是否可用 (Windows兼容增强)
   */
  async checkDockerAvailable() {
    try {
      await execAsync('docker --version');
      
      // Windows环境下额外检查Docker Desktop状态
      if (process.platform === 'win32') {
        try {
          // 检查Docker守护进程是否运行
          await execAsync('docker info', { timeout: 10000 });
          console.log('✅ Windows Docker Desktop 运行正常');
          return true;
        } catch (error) {
          console.log('⚠️  Windows Docker Desktop 可能未启动或配置问题');
          console.log('💡 请确保：');
          console.log('   1. Docker Desktop 已启动');
          console.log('   2. 切换到 Linux 容器模式');
          console.log('   3. 网络连接正常');
          return false;
        }
      }
      
      return true;
    } catch (error) {
      console.log('❌ Docker 不可用:', error.message);
      return false;
    }
  }

  /**
   * 为项目创建Dockerfile
   */
  async createDockerfile(projectPath, nodeVersion = 'node14', platform = 'h5', apiUrl = null) {
    const nodeImage = this.nodeImages[nodeVersion] || this.nodeImages['node14'];
    
    // 强制使用 npm 和指定镜像源
    const packageManager = 'npm';
    const installCommand = 'npm install --registry=https://registry.npmmirror.com';
    let buildCommand = 'npm run build';
    
    console.log('🔧 强制使用 npm 和 npmmirror.com 镜像源');
    
    // Windows环境检测和网络配置
    const isWindows = process.platform === 'win32';
    console.log(`🖥️  检测到运行环境: ${process.platform}${isWindows ? ' (Windows)' : ''}`);
    
    if (isWindows) {
      console.log(`🐳 Windows环境将使用官方Docker Hub镜像`);
    }

    // 读取package.json获取构建脚本
    const packagePath = path.join(projectPath, 'package.json');
    if (await fs.pathExists(packagePath)) {
      const pkg = await fs.readJson(packagePath);
      
      // 检测uni-app项目
      const isUniApp = pkg.dependencies?.['@dcloudio/uni-app'] || 
                      pkg.devDependencies?.['@dcloudio/uni-app'] ||
                      pkg.dependencies?.['@dcloudio/vue-cli-plugin-uni'] ||
                      pkg.devDependencies?.['@dcloudio/vue-cli-plugin-uni'];
      
      if (isUniApp) {
        // uni-app项目，根据平台选择构建命令
        const platformCommands = {
          'h5': 'build:h5',
          'mp-weixin': 'build:mp-weixin',
          'mp-alipay': 'build:mp-alipay',
          'h5-scangzh': 'build:custom h5-scangzh',
          'h5-qywx': 'build:custom h5-qywx',
          'h5-alipaydd': 'build:custom h5-alipaydd',
          'h5-nonghang-zj': 'build:custom h5-nonghang-zj',
          'h5-nonghang-js': 'build:custom h5-nonghang-js',
          'h5-nonghang-js-old': 'build:custom h5-nonghang-js-old',
          'h5-huanzhe': 'build:custom h5-huanzhe',
          'weixin-huanzhe': 'build:custom weixin-huanzhe',
          'alipay-huanzhe': 'build:custom alipay-huanzhe'
        };
        
        console.log(`🔧 平台映射: ${platform} -> ${platformCommands[platform] || 'build:h5'}`);
        
        const buildScript = platformCommands[platform] || 'build:h5';
        
        // 检查package.json中是否有对应的构建脚本
        if (pkg.scripts && pkg.scripts[buildScript]) {
          console.log(`✅ 找到构建脚本: ${buildScript}`);
        } else {
          console.log(`⚠️  未找到构建脚本: ${buildScript}，可用的脚本:`, Object.keys(pkg.scripts || {}));
        }
        
        buildCommand = `npm run ${buildScript}`;
        
        // 添加API URL参数
        if (apiUrl) {
          buildCommand += ` --apiurl=${apiUrl}`;
          console.log(`🌐 添加API URL参数: --apiurl=${apiUrl}`);
        }
        
        console.log(`🔧 检测到uni-app项目，使用构建命令: ${buildCommand} (平台: ${platform})`);
      } else if (pkg.scripts?.build) {
        // 普通项目
        buildCommand = 'npm run build';
        
        // 添加API URL参数
        if (apiUrl) {
          buildCommand += ` --apiurl=${apiUrl}`;
          console.log(`🌐 添加API URL参数: --apiurl=${apiUrl}`);
        }
        
        console.log(`🔧 使用构建命令: ${buildCommand}`);
      } else {
        console.log('⚠️  未找到build脚本，使用默认命令');
      }
    }

    // 动态检测主机架构和容器架构兼容性 (Windows兼容)
    const hostArch = process.arch;
    const hostPlatform = process.platform;
    
    // Windows环境下的架构处理
    let dockerPlatform;
    if (isWindows) {
      // Windows下优先使用linux/amd64，避免架构兼容问题
      dockerPlatform = 'linux/amd64';
      console.log(`🏗️  Windows环境: 强制使用 ${dockerPlatform} 平台以确保兼容性`);
    } else {
      // 非Windows环境按原有逻辑
      dockerPlatform = hostArch === 'arm64' ? 'linux/arm64' : 'linux/amd64';
      console.log(`🏗️  检测到主机架构: ${hostArch}, 使用Docker平台: ${dockerPlatform}`);
    }
    
    // 为 Dockerfile 准备平台变量
    const uniPlatform = platform === 'mp-weixin' ? 'mp-weixin' : platform;
    const outputDir = `dist/build/${uniPlatform}`;

    // Windows环境下的镜像处理策略 - 优先使用官方镜像
    let finalNodeImage = nodeImage;
    if (isWindows) {
      console.log(`🐳 Windows环境使用官方Docker Hub镜像: ${finalNodeImage}`);
      console.log(`💡 如果拉取失败，将自动尝试其他镜像源`);
    }

    const dockerfile = `
# Windows兼容的Node.js镜像配置
FROM ${finalNodeImage}

# 设置工作目录
WORKDIR /app

${isWindows ? `
# Windows环境网络优化 - 配置DNS
RUN echo "nameserver 8.8.8.8" > /etc/resolv.conf && \\
    echo "nameserver 114.114.114.114" >> /etc/resolv.conf
` : ''}

# 安装系统依赖 (完整解决node-gyp问题 - Debian版本)
RUN apt-get update && \\
    apt-get install -y \\
    python2 \\
    python3 \\
    python-is-python3 \\
    build-essential \\
    make \\
    g++ \\
    git \\
    libnode-dev && \\
    rm -rf /var/lib/apt/lists/*

# 修复Python兼容性问题 (node-gyp在某些情况下需要Python2语法)
RUN echo "🐍 配置Python环境兼容性..." && \\
    update-alternatives --install /usr/bin/python python /usr/bin/python2 1 && \\
    update-alternatives --install /usr/bin/python python /usr/bin/python3 2 && \\
    update-alternatives --set python /usr/bin/python2 && \\
    echo "当前Python版本:" && python --version && \\
    echo "Python2路径:" && which python2 && \\
    echo "Python3路径:" && which python3

# 设置Python环境变量 (确保node-gyp正确识别Python)
ENV PYTHON="/usr/bin/python2"
ENV npm_config_python="/usr/bin/python2"
ENV GYP_DEFINES="python_executable=/usr/bin/python2"

# 配置npm镜像源 (Windows环境优化)
RUN npm config set registry https://registry.npmmirror.com/
RUN npm config set sass_binary_site https://npmmirror.com/mirrors/node-sass/
RUN npm config set phantomjs_cdnurl https://npmmirror.com/mirrors/phantomjs/
RUN npm config set electron_mirror https://npmmirror.com/mirrors/electron/
${isWindows ? `
# Windows环境网络优化配置
RUN npm config set fetch-timeout 60000
RUN npm config set fetch-retry-mintimeout 20000
RUN npm config set fetch-retry-maxtimeout 120000
RUN npm config set fetch-retries 3
` : ''}

# 设置构建优化环境变量
ENV SASS_BINARY_SITE=https://npmmirror.com/mirrors/node-sass/
ENV NODE_SASS_SKIP_SASS_BINARY_DOWNLOAD_FOR_CI=0

# 创建.npmrc文件 (仅优化下载镜像)
RUN echo "registry=https://registry.npmmirror.com/" > .npmrc
RUN echo "sass_binary_site=https://npmmirror.com/mirrors/node-sass/" >> .npmrc
RUN echo "phantomjs_cdnurl=https://npmmirror.com/mirrors/phantomjs/" >> .npmrc
RUN echo "electron_mirror=https://npmmirror.com/mirrors/electron/" >> .npmrc

# 复制package文件
COPY package*.json ./
${await fs.pathExists(path.join(projectPath, 'yarn.lock')) ? 'COPY yarn.lock ./' : ''}
${await fs.pathExists(path.join(projectPath, 'pnpm-lock.yaml')) ? 'COPY pnpm-lock.yaml ./' : ''}

# 预安装Vue2 uni-app必需的全局工具
RUN npm install -g @vue/cli@5.0.8 --registry=https://registry.npmmirror.com/ && \\
    echo "✅ Vue CLI安装完成"

# 预安装常用构建工具 (但不强制特定版本)
RUN echo "🔧 安装常用构建工具..." && \\
    echo "让项目自己决定使用哪个Sass实现"

# 安装项目依赖 (按照项目原有配置)
RUN echo "📦 开始安装项目依赖，使用: ${installCommand}" && \\
    ${installCommand}

# 复制源代码
COPY . .

# 构建项目
RUN echo "开始构建项目，使用命令: ${buildCommand}"
RUN echo "检查package.json中的scripts:" && cat package.json | grep -A 20 '"scripts"'
RUN echo "检查当前目录内容:" && ls -la
RUN echo "检查node_modules是否存在:" && ls -la node_modules/ 2>/dev/null || echo "node_modules不存在"
RUN echo "检查npm是否可用:" && npm --version

# Vue2 uni-app构建 (检查Vue版本并适配)
RUN echo "🔍 检查Vue版本..." && \\
    (cat package.json | grep '"vue"' || echo "未找到Vue依赖") && \\
    (cat node_modules/vue/package.json | grep '"version"' 2>/dev/null || echo "无法获取Vue版本")

# 验证依赖安装结果
RUN echo "🔍 验证依赖安装..." && \\
    echo "已安装的包数量:" && \\
    (npm list --depth=0 2>/dev/null | wc -l || echo "无法获取") && \\
    echo "node_modules目录大小:" && \\
    (du -sh node_modules 2>/dev/null || echo "node_modules不存在")

# 设置uni-app构建环境
RUN echo "🔧 设置uni-app构建环境..." && \\
    export UNI_PLATFORM=${uniPlatform} && \\
    export NODE_ENV=production && \\
    export UNI_OUTPUT_DIR=/app/${outputDir}

# 执行构建命令 (使用项目定义的构建脚本)
RUN echo "🚀 开始构建，命令: ${buildCommand}" && \\
    ${buildCommand} 2>&1 | tee build.log

# 检查并修复构建输出目录
RUN echo "🔍 检查构建输出..." && \\
    echo "查找所有可能的输出目录:" && \\
    find . -type d \\( -name "dist" -o -name "build" -o -name "unpackage" \\) -not -path "./node_modules/*" 2>/dev/null | head -10 && \\
    echo "查找微信小程序文件:" && \\
    find . -name "*.wxml" -o -name "*.wxss" -o -name "app.json" -not -path "./node_modules/*" 2>/dev/null | head -20

# 整理构建输出 (尊重项目的输出结构)
RUN echo "📦 整理构建输出..." && \\
    echo "构建完成，项目的输出目录:" && \\
    find . -type d \\( -name "dist" -o -name "build" -o -name "unpackage" \\) -not -path "./node_modules/*" 2>/dev/null | head -10 && \\
    echo "如果项目有自定义输出路径，将保持原样"

RUN echo "构建过程完成，检查输出目录:"

# 显示构建后的目录结构
RUN echo "构建完成，目录结构:" && ls -la

# 检查构建产物
RUN echo "检查dist目录:" && ls -la dist/ 2>/dev/null || echo "dist目录不存在"
RUN echo "检查dist/build目录:" && ls -la dist/build/ 2>/dev/null || echo "dist/build目录不存在"
RUN echo "检查dist/build/mp-weixin目录:" && ls -la dist/build/mp-weixin/ 2>/dev/null || echo "dist/build/mp-weixin目录不存在"
RUN echo "检查unpackage目录:" && ls -la unpackage/ 2>/dev/null || echo "unpackage目录不存在"
RUN echo "检查所有目录:" && find . -type d -maxdepth 3 | head -30
RUN echo "检查所有文件:" && find . -type f -name "*.js" -o -name "*.json" -o -name "*.wxss" -o -name "*.wxml" | head -20
RUN echo "检查构建日志:" && find . -name "*.log" -o -name "build.log" -o -name "error.log" | head -10
RUN echo "检查最近修改的文件:" && find . -type f -mmin -10 | head -20

# 保持容器运行
CMD ["tail", "-f", "/dev/null"]
    `.trim();

    const dockerfilePath = path.join(projectPath, 'Dockerfile.build');
    await fs.writeFile(dockerfilePath, dockerfile);
    
    return dockerfilePath;
  }

  /**
   * 使用Docker构建项目（错误隔离版本）
   */
  async buildWithDocker(projectPath, nodeVersion = 'node14', envVars = {}, platform = 'h5', projectId = null, apiUrl = null) {
    try {
      return await this._performDockerBuild(projectPath, nodeVersion, envVars, platform, projectId, apiUrl);
    } catch (error) {
      // 错误隔离：包装并重新抛出，确保不会导致进程意外退出
      const wrappedError = new Error(`Docker构建隔离错误: ${error.message}`);
      wrappedError.originalError = error;
      wrappedError.code = 'DOCKER_BUILD';
      wrappedError.stdout = error.stdout;
      wrappedError.stderr = error.stderr;
      throw wrappedError;
    }
  }

  /**
   * 内部Docker构建实现
   */
  async _performDockerBuild(projectPath, nodeVersion = 'node14', envVars = {}, platform = 'h5', projectId = null, apiUrl = null) {
    try {
      if (projectId) {
        logManager.sendDockerLog(projectId, `使用Docker构建 (Node ${nodeVersion})`);
      }
      
      // 轻量级依赖检查 (不强制修改项目配置)
      if (projectId) {
        logManager.sendBuildStep(projectId, '依赖检查', '检查项目依赖配置...');
      }
      // await dependencyResolver.resolveAllConflicts(projectPath); // 注释掉，让项目保持原有配置
      
      // 创建Dockerfile
      if (projectId) {
        logManager.sendDockerLog(projectId, '创建Dockerfile配置');
      }
      await this.createDockerfile(projectPath, nodeVersion, platform, apiUrl);
      
      // 生成Docker镜像名
      const imageName = `gitbuild-${path.basename(projectPath)}-${nodeVersion}`.toLowerCase();
      
      // 构建环境变量参数
      const envArgs = Object.entries(envVars)
        .map(([key, value]) => `--build-arg ${key}="${value}"`)
        .join(' ');
      
      // 构建Docker镜像 (Windows网络优化)
      if (projectId) {
        logManager.sendDockerLog(projectId, '开始构建Docker镜像...');
      }
      
      // Windows环境下的构建命令优化
      let buildCommand = `docker build -f Dockerfile.build -t ${imageName} ${envArgs} .`;
      const isWindows = process.platform === 'win32';
      
      if (isWindows) {
        // Windows环境使用简化的构建命令，避免网络参数兼容性问题
        buildCommand = `docker build -f Dockerfile.build -t ${imageName} ${envArgs} .`;
        console.log('🔧 Windows环境使用简化构建命令');
      }
      
      console.log(`🐳 执行构建命令: ${buildCommand}`);
      
      try {
        const { stdout, stderr } = await execAsync(buildCommand, { 
          cwd: projectPath,
          timeout: 1800000, // 30分钟超时
          env: {
            ...process.env,
            // Windows环境下的Docker环境变量优化
            ...(isWindows ? {
              DOCKER_BUILDKIT: '0', // 禁用BuildKit避免网络问题
              BUILDKIT_PROGRESS: 'plain',
              // 网络相关环境变量
              DOCKER_DEFAULT_PLATFORM: 'linux/amd64'
            } : {})
          }
        });
        
        if (projectId) {
          logManager.sendDockerLog(projectId, 'Docker镜像构建成功');
          if (stdout) {
            logManager.sendLog(projectId, {
              level: 'info',
              message: 'Docker构建输出',
              data: { output: stdout.slice(-2000) } // 只显示最后2000字符
            });
          }
        }
        
        if (stderr) {
          if (projectId) {
            logManager.sendLog(projectId, {
              level: 'warning',
              message: 'Docker构建警告',
              data: { warning: stderr.slice(-1000) }
            });
          }
        }
      } catch (error) {
        // Windows环境下处理镜像拉取失败的情况
        if (isWindows && error.stderr && (error.stderr.includes('pull access denied') || error.stderr.includes('repository does not exist'))) {
          if (projectId) {
            logManager.sendLog(projectId, {
              level: 'warning',
              message: '🔄 镜像拉取失败，尝试预拉取官方镜像...',
              data: { error: error.message }
            });
          }
          
          // 尝试预拉取官方镜像
          try {
            console.log('🔄 尝试预拉取官方镜像...');
            await execAsync(`docker pull ${nodeImage}`, { timeout: 300000 }); // 5分钟超时
            
            // 重新创建Dockerfile使用官方镜像
            await this.createDockerfile(projectPath, nodeVersion, platform, apiUrl);
            
            // 重新尝试构建
            console.log('🔄 使用官方镜像重新构建...');
            const { stdout: retryStdout, stderr: retryStderr } = await execAsync(buildCommand, { 
              cwd: projectPath,
              timeout: 1800000,
              env: {
                ...process.env,
                ...(isWindows ? {
                  DOCKER_BUILDKIT: '0',
                  BUILDKIT_PROGRESS: 'plain',
                  DOCKER_DEFAULT_PLATFORM: 'linux/amd64'
                } : {})
              }
            });
            
            if (projectId) {
              logManager.sendDockerLog(projectId, '✅ 使用官方镜像构建成功');
            }
            
            // 构建成功，继续执行后续逻辑
            if (retryStdout) {
              if (projectId) {
                logManager.sendLog(projectId, {
                  level: 'info',
                  message: 'Docker构建输出',
                  data: { output: retryStdout.slice(-2000) }
                });
              }
            }
            
            if (retryStderr) {
              if (projectId) {
                logManager.sendLog(projectId, {
                  level: 'warning',
                  message: 'Docker构建警告',
                  data: { warning: retryStderr.slice(-1000) }
                });
              }
            }
            
          } catch (retryError) {
            if (projectId) {
              logManager.sendBuildError(projectId, {
                message: `Docker镜像构建失败 (重试后): ${retryError.message}`,
                stdout: retryError.stdout,
                stderr: retryError.stderr
              });
            }
            throw retryError;
          }
        } else {
          // 非镜像拉取问题，直接抛出错误
          if (projectId) {
            logManager.sendBuildError(projectId, {
              message: `Docker镜像构建失败: ${error.message}`,
              stdout: error.stdout,
              stderr: error.stderr
            });
          }
          throw error;
        }
      }
      
      // 从容器中复制构建产物
      console.log('📦 提取构建产物...');
      const containerId = await this.createContainer(imageName);
      
      // 启动容器以检查内容
      await execAsync(`docker start ${containerId}`);
      
      // 等待容器完全启动
      await new Promise(resolve => setTimeout(resolve, 2000));
      
      // 列出容器中的目录结构
      console.log('🔍 检查容器目录结构...');
      try {
        const { stdout: lsOutput } = await execAsync(`docker exec ${containerId} ls -la /app/`);
        console.log('📁 容器根目录内容:', lsOutput);
        
        // 检查是否有unpackage目录
        try {
          const { stdout: unpackageLs } = await execAsync(`docker exec ${containerId} ls -la /app/unpackage/`);
          console.log('📁 unpackage目录内容:', unpackageLs);
          
          // 详细检查unpackage目录下的子目录
          const { stdout: unpackageSubDirs } = await execAsync(`docker exec ${containerId} find /app/unpackage -type d -maxdepth 2`);
          console.log('📁 unpackage目录结构:', unpackageSubDirs);
          
          // 检查unpackage目录下的所有文件
          const { stdout: unpackageAllFiles } = await execAsync(`docker exec ${containerId} find /app/unpackage -type f | head -20`);
          console.log('📄 unpackage目录文件:', unpackageAllFiles);
          
        } catch (e) {
          console.log('❌ unpackage目录不存在');
        }
        
        // 检查是否有dist目录
        try {
          const { stdout: distLs } = await execAsync(`docker exec ${containerId} ls -la /app/dist/`);
          console.log('📁 dist目录内容:', distLs);
          
          // 详细检查dist目录下的子目录
          const { stdout: distSubDirs } = await execAsync(`docker exec ${containerId} find /app/dist -type d -maxdepth 2`);
          console.log('📁 dist目录结构:', distSubDirs);
          
          // 检查dist目录下的所有文件
          const { stdout: distAllFiles } = await execAsync(`docker exec ${containerId} find /app/dist -type f | head -20`);
          console.log('📄 dist目录文件:', distAllFiles);
          
        } catch (e) {
          console.log('❌ dist目录不存在');
        }
        
      } catch (error) {
        console.log('⚠️  无法列出容器内容，继续提取...');
      }
      
      // 检测输出目录 - 添加uni-app特有的目录
      const outputDirs = ['dist', 'build', 'out', 'public', 'unpackage', 'unpackage/dist'];
      let outputDir = null;
      
      for (const dir of outputDirs) {
        try {
          await execAsync(`docker exec ${containerId} test -d /app/${dir}`);
          outputDir = dir;
          console.log(`✅ 找到输出目录: ${dir}`);
          
          // 如果是dist目录，检查是否有build子目录
          if (dir === 'dist') {
            try {
              await execAsync(`docker exec ${containerId} test -d /app/dist/build`);
              console.log('✅ 发现dist/build目录，检查平台子目录...');
              
              // 检查dist/build下的平台目录
              const platformDirs = ['mp-weixin', 'h5', 'mp-alipay', 'mp-toutiao', 'mp-baidu'];
              for (const platformDir of platformDirs) {
                try {
                  await execAsync(`docker exec ${containerId} test -d /app/dist/build/${platformDir}`);
                  console.log(`✅ 发现平台目录: dist/build/${platformDir}`);
                  
                  // 显示平台目录内容
                  const { stdout: platformContent } = await execAsync(`docker exec ${containerId} ls -la /app/dist/build/${platformDir}/`);
                  console.log(`📁 dist/build/${platformDir}目录内容:`, platformContent);
                  
                  // 如果是当前构建的平台，设置为输出目录
                  if (platformDir === platform) {
                    outputDir = `dist/build/${platformDir}`;
                    console.log(`🎯 设置为输出目录: ${outputDir}`);
                    break;
                  }
                } catch (e) {
                  console.log(`❌ 平台目录不存在: dist/build/${platformDir}`);
                }
              }
            } catch (e) {
              console.log('❌ dist/build目录不存在');
            }
          }
          
          break;
        } catch (e) {
          console.log(`❌ 目录不存在: ${dir}`);
        }
      }
      
      // 如果是uni-app项目，检查unpackage目录下的子目录
      if (!outputDir) {
        try {
          const { stdout: unpackageContent } = await execAsync(`docker exec ${containerId} ls -la /app/unpackage/`);
          console.log('📁 unpackage目录内容:', unpackageContent);
          
          // 检查unpackage下的子目录
          const unpackageDirs = ['dist', 'build', 'mp-weixin', 'h5', 'mp-alipay'];
          for (const subDir of unpackageDirs) {
            try {
              await execAsync(`docker exec ${containerId} test -d /app/unpackage/${subDir}`);
              outputDir = `unpackage/${subDir}`;
              console.log(`✅ 找到uni-app输出目录: ${outputDir}`);
              break;
            } catch (e) {
              console.log(`❌ unpackage子目录不存在: ${subDir}`);
            }
          }
        } catch (e) {
          console.log('❌ unpackage目录不存在');
        }
      }
      
      if (!outputDir) {
        // 如果没有找到标准输出目录，复制整个app目录
        console.log('⚠️  未找到标准输出目录，复制整个项目...');
        const buildOutputPath = path.join(projectPath, 'docker-build-output');
        await fs.ensureDir(buildOutputPath);
        await execAsync(`docker cp ${containerId}:/app/. ${buildOutputPath}/`);
      } else {
        // 复制构建产物到宿主机
        const buildOutputPath = path.join(projectPath, 'docker-build-output');
        await fs.ensureDir(buildOutputPath);
        await execAsync(`docker cp ${containerId}:/app/${outputDir}/. ${buildOutputPath}/`);
      }
      
      // 停止并清理容器
      await execAsync(`docker stop ${containerId}`);
      await execAsync(`docker rm ${containerId}`);
      
      // 检查最终提取的构建产物
      const buildOutputPath = path.join(projectPath, 'docker-build-output');
      if (await fs.pathExists(buildOutputPath)) {
        const files = await fs.readdir(buildOutputPath);
        console.log('📦 最终构建产物文件:', files);
        
        // 递归检查子目录
        for (const file of files) {
          const filePath = path.join(buildOutputPath, file);
          const stat = await fs.stat(filePath);
          if (stat.isDirectory()) {
            const subFiles = await fs.readdir(filePath);
            console.log(`📁 ${file}目录内容:`, subFiles);
            
            // 特别检查dist目录
            if (file === 'dist') {
              console.log('🔍 详细检查dist目录内容:');
              for (const subFile of subFiles) {
                const subFilePath = path.join(filePath, subFile);
                const subStat = await fs.stat(subFilePath);
                if (subStat.isDirectory()) {
                  const subSubFiles = await fs.readdir(subFilePath);
                  console.log(`  📁 dist/${subFile}目录内容:`, subSubFiles);
                  
                  // 特别检查build目录下的mp-weixin
                  if (subFile === 'build') {
                    console.log('🔍 详细检查dist/build目录内容:');
                    for (const buildSubFile of subSubFiles) {
                      const buildSubFilePath = path.join(subFilePath, buildSubFile);
                      const buildSubStat = await fs.stat(buildSubFilePath);
                      if (buildSubStat.isDirectory()) {
                        const buildSubSubFiles = await fs.readdir(buildSubFilePath);
                        console.log(`    📁 dist/build/${buildSubFile}目录内容:`, buildSubSubFiles);
                        
                        // 如果是mp-weixin目录，显示详细信息
                        if (buildSubFile === 'mp-weixin') {
                          console.log('🔍 详细检查mp-weixin目录内容:');
                          for (const wxFile of buildSubSubFiles) {
                            const wxFilePath = path.join(buildSubFilePath, wxFile);
                            const wxStat = await fs.stat(wxFilePath);
                            if (wxStat.isDirectory()) {
                              const wxSubFiles = await fs.readdir(wxFilePath);
                              console.log(`      📁 dist/build/mp-weixin/${wxFile}目录内容:`, wxSubFiles);
                            } else {
                              console.log(`      📄 dist/build/mp-weixin/${wxFile} (文件)`);
                            }
                          }
                        }
                      } else {
                        console.log(`    📄 dist/build/${buildSubFile} (文件)`);
                      }
                    }
                  }
                } else {
                  console.log(`  📄 dist/${subFile} (文件)`);
                }
              }
            }
          }
        }
      }
      
      console.log('✅ Docker构建完成');
      
      return {
        success: true,
        outputDir: 'docker-build-output',
        buildMethod: 'docker',
        nodeVersion: this.nodeImages[nodeVersion]
      };
      
    } catch (error) {
      console.error('Docker构建失败:', error);
      throw error;
    }
  }

  /**
   * 创建临时容器
   */
  async createContainer(imageName) {
    const { stdout } = await execAsync(`docker create ${imageName}`);
    return stdout.trim();
  }

  /**
   * 清理Docker资源
   */
  async cleanup(projectPath) {
    try {
      const imageName = `gitbuild-${path.basename(projectPath)}`;
      
      // 删除相关镜像
      const { stdout } = await execAsync(`docker images -q ${imageName}*`);
      const imageIds = stdout.trim().split('\n').filter(id => id);
      
      if (imageIds.length > 0) {
        await execAsync(`docker rmi ${imageIds.join(' ')}`);
        console.log(`🗑️  清理了 ${imageIds.length} 个Docker镜像`);
      }
      
      // 删除Dockerfile
      const dockerfilePath = path.join(projectPath, 'Dockerfile.build');
      if (await fs.pathExists(dockerfilePath)) {
        await fs.remove(dockerfilePath);
      }
      
    } catch (error) {
      console.warn('Docker清理警告:', error.message);
    }
  }
}

module.exports = new DockerBuildManager();
